//
//  RHDeviceParaSetListVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/7/31.
//

#import "RHDeviceParaSetListVC.h"
#import "RHDevParaModel.h"
#import "ChoiceEndpointVC.h"
#import "RHChartHeaderView.h"
#import "RHParaSettingCell.h"
#import "RHChoiceParaView.h"
#import "WSDatePickerView.h"
#import "PasswordVerifyController.h"
#import "RHWindowTipManage.h"
#import "RHTools.h"
#import "KWTTimePickerView.h"
#import "NetworkConfig.h"

@interface RHDeviceParaSetListVC ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic ,strong) UITableView *tableView;
//指令
@property (nonatomic,strong) NSMutableArray *cmdArray;
//参数
@property (nonatomic,strong) NSMutableArray *paraArray;
//参数+指令
@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic ,strong) RHChartHeaderView *headerView;

@property (nonatomic,strong) RHEndPointModel *endPointModel;

@property (nonatomic ,assign) BOOL isReadPara;//是否读取参数
@end

@implementation RHDeviceParaSetListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.cmdArray = [NSMutableArray array];
    self.paraArray = [NSMutableArray array];
    self.dataArray = [NSMutableArray array];
    [self setupUI];
}

-(void)setEndPointTypeModel:(RHEndPointTypeModel *)endPointTypeModel
{
    _endPointTypeModel = endPointTypeModel;
    if(endPointTypeModel.nodes.count>0){
        self.endPointModel = [endPointTypeModel.nodes firstObject];
        //指令已改为放在参数设置参数里了
//        [self getCommandList];
        [self getEndPointParaList];
    }
}

//更新端点下的子端点在线状态
-(void)updateEndpointTypeModel:(RHEndPointTypeModel*)typeModel
{
    if (self.endPointTypeModel.endpointTypeId == typeModel.endpointTypeId) {
        [self.endPointTypeModel.nodes enumerateObjectsUsingBlock:^(RHEndPointModel * _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
            [typeModel.nodes enumerateObjectsUsingBlock:^(RHEndPointModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([model.sn isEqualToString:obj.sn]) {
                    model.state = obj.state;
                }
            }];
        }];
    }
    self.headerView.endPointModel = self.headerView.endPointModel;
}

#pragma mark ------- 1. 获取指令列表,只取第一层

-(void)getCommandList
{
    if (self.deviceModel.deviceId.length == 0 || self.endPointModel.endpointCode.length == 0) {
        [self.tableView endHeaderRefresh];
        return;
    }
    NSLog(@"----->111");
    [self.dataArray removeAllObjects];
    [self.cmdArray removeAllObjects];
    [self.paraArray removeAllObjects];
    [RHDevParaModel startWithCompletionAPIKey:H_getDevCommandList argument:@{@"deviceTypeCode":self.deviceModel.deviceTypeCode,@"endpointTypeCode":self.endPointModel.endpointCode} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200 ){
            NSArray *arr = resultModel.data;
            [self.cmdArray removeAllObjects];
            [self.paraArray removeAllObjects];
            if(arr.count > 0){
                RHDevParaModel *commandModel = [[RHDevParaModel alloc]init];
                commandModel.dateType = @"command";
                commandModel.thresholdParamConfigVos = arr;
                self.cmdArray =@[commandModel].mutableCopy;
            }
            [self.dataArray addObjectsFromArray:self.cmdArray.copy];
//            [self.tableView reloadData];
        }
        [self getEndPointParaList];
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
}

#pragma mark -------2. 获取参数列表 --------
-(void)getEndPointParaList
{
    NSLog(@"---->222");
    
    if(self.endPointModel==nil)return;
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"endpointTypeCode":self.endPointModel.endpointCode,
                           @"deviceId":self.deviceModel.deviceId,
                           @"sn":self.endPointModel.sn,
                           @"deviceTypeCode":self.deviceModel.deviceTypeCode
    } ;
    [RHDevParaModel startWithCompletionAPIKey:H_devParameterConfig argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if(resultModel.code == 200){
                NSArray *arr = resultModel.data;
                [self.paraArray removeAllObjects];
                [self.dataArray removeAllObjects];
                //逆变器添加时间校准
                if ([self.endPointModel.endpointCode isEqualToString:@"InvMegarevoLv"]) {
                    [self addInverter3SystemVeritifyData];
                }
                //Ems时间校准  ,寄存器使用地址是两个参数共用一个地址,先不加,设备暂时处理不了
                //后面新定义了6个字段统一处理时间校准问题
                if ([self.endPointModel.endpointCode isEqualToString:@"EMS"])
                {
                    [self addEmsSystemVeritifyData];
                }
                [arr enumerateObjectsUsingBlock:^(RHDevParaModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                   
                    if(obj.display){
                        __block  BOOL isReadOnly = YES;
                        //遍历下一层,去除不需要展示的参数
                        NSMutableArray *subArr = [NSMutableArray array];
                        [obj.thresholdParamConfigVos enumerateObjectsUsingBlock:^(RHDevParaModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                            if(obj.display){
                                [subArr addObject:obj];
                            }
                            //只要有一个不是只读,整组都不是只读
                            if(obj.readOnly == NO){
                                isReadOnly = NO;
                            }
                            
                            if ([obj.paramName isEqualToString:@"Ems_InterAddr"]) {
                                //EMS 逆变器地址设置,针对 品牌 高低压做一下筛选
                                [self filterInvAddress:obj];
                                
                            }
                        }];
                        obj.readOnly = isReadOnly;
                        obj.thresholdParamConfigVos = subArr.copy;
                        [self.paraArray addObject:obj];
                    }
                }];
                [self.dataArray addObjectsFromArray:self.cmdArray.copy];
                [self.dataArray addObjectsFromArray:self.paraArray.copy];
                [self.tableView reloadData];
                //获取参数值
                [self getParamStatusData];
            }
            [self.tableView endHeaderRefresh];
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            [self.tableView endHeaderRefresh];
    }];
}

#pragma mark ------  EMS 添加时间校准
-(void)addEmsSystemVeritifyData
{
    RHDevParaModel *sectionModel = [[RHDevParaModel alloc]init];
    sectionModel.display = YES;
    sectionModel.thresholdCode = @"Ems_Systime";
    sectionModel.thresholdName = @"系统时间校准".rh_localized;
    
    RHDevParaModel *rowModel = [[RHDevParaModel alloc]init];
    rowModel.display = YES;
    rowModel.paramName = @"Ems_systemTime";
    rowModel.paramNickName = @"时间校准".rh_localized;
    rowModel.dateType = @"dateTime";
    sectionModel.thresholdParamConfigVos = @[rowModel];
    [self.paraArray addObject:sectionModel];
}

#pragma mark ------ 根据品牌,高低压过滤逆变器品牌
-(void)filterInvAddress:(RHDevParaModel*)paraModel
{
    NSMutableArray *enumIndexs = [NSMutableArray array];
    NSMutableArray *enumValues = [NSMutableArray array];
    __block NSInteger min = 0;
    __block NSInteger max = 0;
    if ([PrivateMange share].currentUser.topBrandId == brand_id_kwt.integerValue) {//科威特
        if (self.deviceModel.isHighVoltage) {
            min = 700;
            max = 800;
        }else{
            min = 500;
            max = 600;
        }
    }
    if ([PrivateMange share].currentUser.topBrandId == brand_id_renon.integerValue) {//瑞诺
        if (self.deviceModel.isHighVoltage) {
            min = 300;
            max = 400;
        }else{
            min = 100;
            max = 200;
        }
    }
    if ([PrivateMange share].currentUser.topBrandId == brand_id_zrgp.integerValue) {//中瑞
        if (self.deviceModel.isHighVoltage) {
            min = 1100;
            max = 1200;
        }else{
            min = 900;
            max = 1000;
        }
    }
    [paraModel.enumArr enumerateObjectsUsingBlock:^(NSString*  _Nonnull indexStr, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if ([indexStr integerValue]>=min && [indexStr integerValue] < max) {
            [enumIndexs addObject:indexStr];
            [enumValues addObject:[paraModel.enumNameArr safeObjectAtIndex:idx]];
        }
    }];
    if (enumIndexs.count>0 && (enumIndexs.count == enumValues.count)) {
        paraModel.enumArr = enumIndexs.copy;
        paraModel.enumNameArr = enumValues.copy;
    }
    
}

#pragma mark ------ 3.获取参数值
-(void)getParamStatusData
{
    [QMUITips showLoadingInView:self.view];
    [BaseModel startGetWithCompletionAPIKey:H_getParamStatusData argument:@{@"deviceId":ValidNullData(self.deviceModel.deviceId),@"sn":ValidNullData(self.endPointModel.sn)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            NSDictionary *dataDic = request.responseJSONObject[@"data"];
            [self.dataArray enumerateObjectsUsingBlock:^(RHDevParaModel  *_Nonnull paraModel, NSUInteger idx, BOOL * _Nonnull stop) {
                __block BOOL isAllNanValue = YES;//标志这组参数中是不是都是32767的异常温度数据
                //指令数据不加载
                if(![paraModel.dateType isEqualToString:@"command"]) {
                    [paraModel.thresholdParamConfigVos enumerateObjectsUsingBlock:^(RHDevParaModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        
                        obj.currentValue = ValidNullData(dataDic[obj.paramName]);
                        
                        if ([obj.currentValue integerValue]!=32767) {
                            isAllNanValue = NO;
                        }
                        //如果是系统时间 ,纳通  户用的设备上显示的是北京时间 ,要转成 当前的时区
                        if ([obj.paramName isEqualToString:@"Ems_systemTime"]) {
                            //时间校准  ,这个是只写的  不读取  ,所以不用显示,显示当前系统时间就好了
                            NSString *timeStr = [NSString stringWithFormat:@"%02ld/%02ld/%02ld %02ld:%02ld:%02ld",[dataDic[@"Ems_CloudYear"] integerValue],[dataDic[@"Ems_CloudMon"] integerValue],[dataDic[@"Ems_CloudDay"] integerValue],[dataDic[@"Ems_CloudHour"] integerValue],[dataDic[@"Ems_CloudMin"] integerValue],[dataDic[@"Ems_CloudSec"] integerValue]];
                            obj.currentValue = timeStr;
                            //针对户用设备
                            if (self.deviceModel.productTypeId == ProductType_HE_BAT||
                                self.deviceModel.productTypeId == ProductType_HE_ALLINONE) {
                                obj.currentValue = [NSDate beiJinTimeConvertToLocalTime:timeStr];
                            }
                        }
                        //如果是迈格瑞能系统时间
                        if ([obj.paramName isEqualToString:@"Inv3_systemTime"]) {
                            //时间校准
                            obj.currentValue = [NSString stringWithFormat:@"20%02ld/%02ld/%02ld %02ld:%02ld:%02ld",[dataDic[@"Inv3_RTCYear"] integerValue],[dataDic[@"Inv3_RTCMonth"] integerValue],[dataDic[@"Inv3_RTCDay"] integerValue],[dataDic[@"Inv3_RTCHour"] integerValue],[dataDic[@"Inv3_RTCMinute"] integerValue],[dataDic[@"Inv3_RTCSecond"] integerValue]];
                        }
                    }];
                }
                paraModel.canCommit = !isAllNanValue;//全是32767的异常温度数据时 提交按钮不可点击
                
            }];
            [self.tableView reloadData];
            if (self.isReadPara) {
                [QMUITips showSucceed:@"读取成功".rh_localized inView:self.view hideAfterDelay:1];
                self.isReadPara = NO;
            }
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        
    }];
}


-(void)addInverter3SystemVeritifyData
{
    RHDevParaModel *sectionModel = [[RHDevParaModel alloc]init];
    sectionModel.display = YES;
    sectionModel.thresholdCode = @"systime";
    sectionModel.thresholdName = @"系统时间校准".rh_localized;
    
    RHDevParaModel *rowModel = [[RHDevParaModel alloc]init];
    rowModel.display = YES;
    rowModel.paramName = @"Inv3_systemTime";
    rowModel.paramNickName = @"时间校准".rh_localized;
    rowModel.dateType = @"dateTime";
    sectionModel.thresholdParamConfigVos = @[rowModel];
    [self.paraArray addObject:sectionModel];
}

#pragma mark -------- 密码校验
-(void)checkPassword:(RHDevParaModel*)settingModel
{
    //参数的body
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    [settingModel.thresholdParamConfigVos enumerateObjectsUsingBlock:^(RHDevParaModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        //显示并且 不是只读属性的才修改
        if(obj.display&&obj.readOnly==NO){
            if(obj.currentValue.length == 0)return;
            NSString *value = ValidNullData(obj.currentValue);
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:[NSDecimalNumber decimalNumberWithString:value] forKey:@"value"];
            [dic setObject:obj.dateType forKey:@"dataType"];
            [dic setObject:obj.paramName forKey:@"paramName"];
            [dic setObject:@(obj.regAddr) forKey:@"regAddr"];
            [dic setObject:@(obj.num) forKey:@"num"];
            [dic setObject:@(obj.offset) forKey:@"offset"];
            
            [paraListArr addObject:dic];
        }
    }];
    
    if ([settingModel.dateType isEqualToString:@"command"]) {
        if (settingModel.currentValue.length == 0) {
            [QMUITips showInfo:@"请输入参数".rh_localized];
            return;
        }
    }else{
        if (paraListArr.count == 0) {
            [QMUITips showInfo:@"请输入参数".rh_localized];
            return;
        }
    }
    
    //先屏蔽密码校验
    if (Password_Check) {
        PasswordVerifyController *vc = [[PasswordVerifyController alloc] init];
        [[RHWindowTipManage shareWindowTipManage] showWithController:vc];

        kWeakSelf;
        vc.callBackBlock = ^(NSString * _Nonnull password) {
            NSDictionary *dic = [RHTools getAccountInfo];
            if ([SafeStr(dic[@"password"]) isEqualToString:password]) {
                if ([settingModel.dateType isEqualToString:@"command"]) {
                    [weakSelf commandAction:settingModel];
                }else{
                    [weakSelf setParamterWithModel:settingModel];
                }
               
            }else{
                [QMUITips showInfo:@"密码错误".rh_localized];
            }
        };
    }else{
        if ([settingModel.dateType isEqualToString:@"command"]) {
            [self commandAction:settingModel];
        }else{
            [self setParamterWithModel:settingModel];
        }
    }

    
    
}


#pragma mark ------ 修改参数 -------
-(void)setParamterWithModel:(RHDevParaModel*)settingModel
{
    [self.view endEditing:YES];
    
    if(!self.endPointModel)return;
    
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    NSDictionary *endPointDic = @{@"dataType":@"string",
                                  @"paramName":@"sn",
                                  @"value":self.endPointModel.sn};
    [paraListArr addObject:endPointDic];
    
    [settingModel.thresholdParamConfigVos enumerateObjectsUsingBlock:^(RHDevParaModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        //如果是枚举,没有匹配到,不提交
        if (obj.isEnum) {
            __block NSInteger index = -1;
            [obj.enumArr enumerateObjectsUsingBlock:^(NSString *_Nonnull idxStr, NSUInteger idx, BOOL * _Nonnull stop) {
                if([obj.currentValue isEqualToString:idxStr]){
                    index = idx;
                    *stop = YES;
                }
            }];
            if (index == -1) {
                return;
            }
        }
        
        //时间校准 参数组装
        if (obj.currentValue.length>0 && [obj.paramName isEqualToString:@"Inv3_systemTime"]) {
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            formatter.dateFormat = @"yyyy/MM/dd HH:mm:ss";
            NSDate *date = [formatter dateFromString:obj.currentValue];
            [self processTimeParams:paraListArr date:date];
            return;
        }
        
        //时间校准 参数组装  Ems
        if (obj.currentValue.length>0 && [obj.paramName isEqualToString:@"Ems_systemTime"]) {
            
            //户用的要把当前时区的时间转成北京时间发送
            if (self.deviceModel.productTypeId == ProductType_HE_BAT||self.deviceModel.productTypeId == ProductType_HE_ALLINONE) {
                NSString *localTimeString = [obj.currentValue stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
                //将当前的时间转成北京时间发给设备
                NSString *bejinDate = [NSDate localTimeConvertToBeiJinTime:localTimeString];
                
                [self processTimeParams:paraListArr dateString:bejinDate];
            }else{
                NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                formatter.dateFormat = @"yyyy/MM/dd HH:mm:ss";
                NSDate *date = [formatter dateFromString:obj.currentValue];
                [self processEmsTimeParams:paraListArr date:date];
            }
            
            return;
        }
        
        //显示并且 不是只读属性的才修改
        if(obj.display&&obj.readOnly==NO){
            if(obj.currentValue.length == 0)return;
            NSString *value = [NSDecimalNumber decimalStringWithDoubleString:ValidNullData(obj.currentValue) nullStr:@"0"];
            if ([obj.dateType isEqualToString:@"string"]) {
                value = obj.currentValue;
            }
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:value forKey:@"value"];
            [dic setObject:obj.dateType forKey:@"dataType"];
            [dic setObject:obj.paramName forKey:@"paramName"];
            [dic setObject:@(obj.regAddr) forKey:@"regAddr"];
            [dic setObject:@(obj.num) forKey:@"num"];
            [dic setObject:@(obj.offset) forKey:@"offset"];
            if ([obj.paramName isEqualToString:@"Inv2_PassWord"]) {//纳通密码补足4位
                [dic setObject:[NSString stringWithFormat:@"%04ld",[value integerValue]] forKey:@"value"];
            }

            [paraListArr addObject:dic];
        }
        
        //233 异常温度值 32767 不提交
        if ([obj.currentValue integerValue]==32767) {
            return;
        }
        
    }];
    
    if (paraListArr.count == 1) {
        [QMUITips showInfo:@"请输入参数".rh_localized];
        return;
    }
    
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
        @"deviceId": self.deviceModel.deviceId,
        @"deviceType": self.deviceModel.productTypeCode,
        @"endpointCode":self.endPointModel.endpointCode,
        @"paramCount":@(paraListArr.count-1),
        @"sn":self.endPointModel.sn,
        @"messageType": @(1),//下行
        @"namespace": @"ParamSetSingle",
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    
    [QMUITips showLoading:@"设置中...".rh_localized inView:self.view];
    [RHDevParaModel startWithCompletionAPIKey:H_controlDevice argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"设置成功".rh_localized];
            
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];

}



#pragma mark ------- 处理麦格瑞能时间校准格式
-(void)processTimeParams:(NSMutableArray*)paramList date:(NSDate*)date
{
    NSArray *keys = @[@"Inv3_RTCYear",@"Inv3_RTCMonth",@"Inv3_RTCDay",@"Inv3_RTCHour",@"Inv3_RTCMinute",@"Inv3_RTCSecond"];
    NSArray *value = @[@(date.year%100),@(date.month),@(date.day),@(date.hour),@(date.minute),@(date.second)];
    [keys enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *timeDic = [NSMutableDictionary dictionary];
        NSString *valueStr = [NSString stringWithFormat:@"%02ld",[value[idx] integerValue]];
        [timeDic setObject:@"int" forKey:@"dataType"];
        [timeDic setObject:keys[idx] forKey:@"paramName"];
        [timeDic setObject:valueStr forKey:@"value"];
        [timeDic setObject:@(1160+idx) forKey:@"regAddr"];//1160-1165
        [timeDic setObject:@(16) forKey:@"num"];
        [timeDic setObject:@(0) forKey:@"offset"];
        [paramList addObject:timeDic];
    }];
   
}

#pragma mark ------- 处理Ems 时间校准格式
-(void)processEmsTimeParams:(NSMutableArray*)paramList date:(NSDate*)date
{
    NSArray *keys = @[@"Ems_CloudYear",@"Ems_CloudMon",@"Ems_CloudDay",@"Ems_CloudHour",@"Ems_CloudMin",@"Ems_CloudSec"];
    NSArray *value = @[@(date.year),@(date.month),@(date.day),@(date.hour),@(date.minute),@(date.second)];
    NSArray *regAddrs = @[@(5103),@(5104),@(5105),@(5106),@(5107),@(5108)];
    [keys enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *timeDic = [NSMutableDictionary dictionary];
        NSString *valueStr = [NSString stringWithFormat:@"%02ld",[value[idx] integerValue]];
        [timeDic setObject:@"int" forKey:@"dataType"];
        [timeDic setObject:keys[idx] forKey:@"paramName"];
        [timeDic setObject:valueStr forKey:@"value"];
        [timeDic setObject:regAddrs[idx] forKey:@"regAddr"];//5103-5108
        [timeDic setObject:@(16) forKey:@"num"];
        [timeDic setObject:@(0) forKey:@"offset"];
        [paramList addObject:timeDic];
    }];
   
}

-(void)processTimeParams:(NSMutableArray*)paramList dateString:(NSString*)dateString
{
    NSString *seperatorKey = @"/";
    if ([dateString containsString:@"-"]) {
        seperatorKey = @"-";
    }
    NSArray *keys = @[@"Ems_CloudYear",@"Ems_CloudMon",@"Ems_CloudDay",@"Ems_CloudHour",@"Ems_CloudMin",@"Ems_CloudSec"];
    NSString *yearStr = [[dateString componentsSeparatedByString:@" "]firstObject];
    NSString *timeStr = [[dateString componentsSeparatedByString:@" "]lastObject];
    NSArray *yearArr = [yearStr componentsSeparatedByString:seperatorKey];
    NSArray *timeArr = [timeStr componentsSeparatedByString:@":"];

    NSInteger year  = [[yearArr safeObjectAtIndex:0] integerValue];
    NSInteger month = [[yearArr safeObjectAtIndex:1] integerValue];
    NSInteger day   = [[yearArr safeObjectAtIndex:2] integerValue];
    NSInteger hour   = [[timeArr safeObjectAtIndex:0] integerValue];
    NSInteger minute = [[timeArr safeObjectAtIndex:1] integerValue];
    NSInteger second = [[timeArr safeObjectAtIndex:2] integerValue];
    
    NSArray *value = @[@(year),@(month),@(day),@(hour),@(minute),@(second)];
    [keys enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *timeDic = [NSMutableDictionary dictionary];
        NSString *valueStr = [NSString stringWithFormat:@"%02ld",[value[idx] integerValue]];
        [timeDic setObject:@"int" forKey:@"dataType"];
        [timeDic setObject:keys[idx] forKey:@"paramName"];
        [timeDic setObject:valueStr forKey:@"value"];
        [timeDic setObject:@(5103+idx) forKey:@"regAddr"];//5103-5108
        [timeDic setObject:@(16) forKey:@"num"];
        [timeDic setObject:@(0) forKey:@"offset"];
        [paramList addObject:timeDic];
    }];
   
}


#pragma mark ------- 设置参数成功的回读
-(void)readParamData:(RHDevParaModel*)settingModel
{
    [self.view endEditing:YES];
    if(!self.endPointModel)return;
    self.isReadPara = YES;
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    NSDictionary *endPointDic = @{@"dataType":@"string",
                                  @"paramName":@"sn",
                                  @"value":self.endPointModel.sn};
    [paraListArr addObject:endPointDic];
    
    [settingModel.thresholdParamConfigVos enumerateObjectsUsingBlock:^(RHDevParaModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        //时间校准 参数组装
        if (obj.currentValue.length>0 && [obj.paramName isEqualToString:@"Inv3_systemTime"]) {
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            formatter.dateFormat = @"yyyy/MM/dd HH:mm:ss";
            NSDate *date = [formatter dateFromString:obj.currentValue];
            [self processTimeParams:paraListArr date:date];
            return;
        }
        
        //时间校准 参数组装  Ems  (不用读取)
        if (obj.currentValue.length>0 && [obj.paramName isEqualToString:@"Ems_systemTime"]) {
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            formatter.dateFormat = @"yyyy/MM/dd HH:mm:ss";
            NSDate *date = [formatter dateFromString:obj.currentValue];
            [self processEmsTimeParams:paraListArr date:date];
            return;
        }
        
        //显示并且 不是只读属性的才修改
        if(obj.display){
            //读取指令不用管有没有值,只上传字段就行
//            if(obj.currentValue.length == 0)return;
            NSString *value = ValidNullDataToString(obj.currentValue, @"1");
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:[NSDecimalNumber decimalNumberWithString:value] forKey:@"value"];
            [dic setObject:obj.dateType forKey:@"dataType"];
            [dic setObject:obj.paramName forKey:@"paramName"];
            [dic setObject:@(obj.regAddr) forKey:@"regAddr"];
            [dic setObject:@(obj.num) forKey:@"num"];
            [dic setObject:@(obj.offset) forKey:@"offset"];
            
            [paraListArr addObject:dic];
        }
    }];
    
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
        @"deviceId": self.deviceModel.deviceId,
        @"deviceType": self.deviceModel.productTypeCode,
        @"endpointCode":self.endPointModel.endpointCode,
        @"paramCount":@(paraListArr.count-1),
        @"sn":self.endPointModel.sn,
        @"messageType": @(1),//下行
        @"namespace": @"ParamReadSingle",
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    
    [QMUITips showLoading:@"".rh_localized inView:self.view];
    [RHDevParaModel startWithCompletionAPIKey:H_controlDevice argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [self getParamStatusData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
}

#pragma mark ------- 选择校准时间 -----------------------
- (void)dateAction:(RHDevParaModel *)settingModel {
 
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDayHourMinuteSecond CompleteBlock:^(NSDate *selectDate) {
        NSString *dateFormatStr = @"yyyy/MM/dd HH:mm:ss";
        NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];
        settingModel.currentValue = currentDate;
        [self.tableView reloadData];
    }];
    datePickerV.dateLabelColor = FontColor(@"#3ECE80");//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    [datePickerV show];
}

#pragma mark ------- 选择充放电时间 -----------------------
-(void)selectTimeAction:(RHDevParaModel*)settingModel{
    kWeakSelf;
    KWTTimePickerView *pick = [[KWTTimePickerView alloc]initWithTitle:@"" deviceType:self.deviceModel.deviceTypeCode CompleteBlock:^(NSString * _Nonnull time) {
        settingModel.currentValue = [time stringByReplacingOccurrencesOfString:@":" withString:@""];
        [weakSelf.tableView reloadData];
    }];
    
    NSInteger hour = [settingModel.currentValue integerValue]/100;
    NSInteger minute = [settingModel.currentValue integerValue]%100;
    NSString *timeStr = [NSString stringWithFormat:@"%02ld:%02ld",hour,minute];
    [pick setCurrentTime:timeStr];
    [pick show];
}

#pragma mark ------ 指令设置 ---------
-(void)commandAction:(RHDevParaModel *)cmdModel
{
    [self.view endEditing:YES];
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
   
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    NSDictionary *endPointDic = @{@"dataType":@"string",
                                  @"paramName":@"sn",
                                  @"value":self.endPointModel.sn};
    [paraListArr addObject:endPointDic];
    
    NSString *cmdValue = @"";
    //指令值,配的是枚举
    
    if (cmdModel.enumArr.count > 1) {
        cmdValue = cmdModel.currentValue;
    }else if (cmdModel.enumArr.count == 1) {
        cmdValue = [cmdModel.enumArr firstObject];
    }else{
        //没有枚举,手输值  要判断 上下限
        cmdValue = ValidNullDataToString(cmdModel.currentValue, @"0");
    }
    if (cmdValue.length == 0) {//一个是设备没有上传参数值,一个是不在枚举选项里
        return;
    }
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:cmdValue forKey:@"value"];
    [dic setObject:@"command" forKey:@"dataType"];
    [dic setObject:cmdModel.paramName forKey:@"paramName"];
    [dic setObject:@(cmdModel.regAddr) forKey:@"regAddr"];
    [dic setObject:@(cmdModel.num) forKey:@"num"];
    [dic setObject:@(cmdModel.offset) forKey:@"offset"];
    [paraListArr addObject:dic];
       
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
        @"deviceId": self.deviceModel.deviceId,
        @"deviceType": self.deviceModel.productTypeCode,
        @"endpointCode":self.endPointModel.endpointCode,
        @"paramCount":@(paraListArr.count-1),
        @"sn":self.endPointModel.sn,
        @"messageType": @(1),//下行
        @"namespace": @"ParamSetSingle",
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    
//    NSLog(@"---->发送的参数:%@",requestPara);
//    return;
    [QMUITips showLoading:@"设置中...".rh_localized inView:self.view];
    [RHDevParaModel startWithCompletionAPIKey:H_controlDevice argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"设置成功".rh_localized];
            
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}


#pragma mark ------ 选择枚举项
-(void)selectAction:(RHDevParaModel*)setttingModel
{
    RHChoiceParaView *paraView = [[RHChoiceParaView alloc]init];
    paraView.curParaModel = setttingModel;
    paraView.choiceResultBlock = ^(RHDevParaModel * _Nonnull model) {
        [self.tableView reloadData];
    };
    [paraView showAnimation];
}


-(void)setupUI
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView registerClass:[RHParaSettingCell class] forCellReuseIdentifier:SettingAddSubCell];
    [_tableView registerClass:[RHParaSettingCell class] forCellReuseIdentifier:SettingTextInputCell];
    [_tableView registerClass:[RHParaSettingCell class] forCellReuseIdentifier:SettingSelectCell];
    [_tableView registerClass:[RHParaSettingCell class] forCellReuseIdentifier:SettingSwitchCell];
    [_tableView registerClass:[RHParaSettingCell class] forCellReuseIdentifier:SettingCommandCell];
    [_tableView registerClass:[RHParaSettingCell class] forCellReuseIdentifier:SettingDateCell];
    [_tableView registerClass:[RHParaSettingCell class] forCellReuseIdentifier:SettingSystemTimeCell];
    [_tableView setSeparatorColor:kRGB(240, 240, 240) ];
    _tableView.tableHeaderView = self.headerView;
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [self.view addSubview:_tableView];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
    kWeakSelf;
    [_tableView addHeaderRefresh:^{
        weakSelf.isReadPara = NO;
        [weakSelf getEndPointParaList];
        if (weakSelf.updateDevStatus) {
            weakSelf.updateDevStatus();
        }
    }];
    
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(0);
        make.top.mas_offset(0);
        make.right.mas_offset(0);
        make.bottom.mas_offset(0);
    }];
}

- (UIView *)headerView{
    if(!_headerView){
        _headerView = [[RHChartHeaderView alloc]init];
        _headerView.frame = CGRectMake(0, 0, kUI_WINDOW_W, kScaleW(45)*2+10);
        _headerView.endpointName = self.endPointTypeModel.endpointTypeName;
        if(self.endPointTypeModel.nodes.count>0){
            _headerView.endPointModel = [self.endPointTypeModel.nodes firstObject];
        }
        kWeakSelf;
        _headerView.selectBlock = ^{
            [UIView animateWithDuration:0.2 animations:^{
                weakSelf.headerView.arrowImg.transform = CGAffineTransformMakeRotation(M_PI/2);
            }];
            
            ChoiceEndpointVC *vc = [[ChoiceEndpointVC alloc]init];
            vc.dataList = weakSelf.endPointTypeModel.nodes;
            vc.curModel = weakSelf.endPointModel;
            [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
            [vc showAnimation];
            vc.choiceResultBlock = ^(RHEndPointModel * _Nonnull model) {
                if (model) {
                    weakSelf.endPointModel = model;
                    weakSelf.headerView.endPointModel = model;
                    //选择了小模块,重新获取参数列表
                    [weakSelf getCommandList];
                }
                
                [UIView animateWithDuration:0.2 animations:^{
                    weakSelf.headerView.arrowImg.transform = CGAffineTransformIdentity;
                }];
                
            };
        };
    }
    return _headerView;
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //指令
    RHDevParaModel *paraModel = self.dataArray[section];
    if([paraModel.dateType isEqualToString:@"command"]){
        return paraModel.thresholdParamConfigVos.count;
    }
    return paraModel.thresholdParamConfigVos.count;
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  
    return  UITableViewAutomaticDimension;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
   
    return 55;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    RHDevParaModel *paraModel = self.dataArray[section];
    RHDevParaModel *rowModel = [paraModel.thresholdParamConfigVos firstObject];
    if([rowModel.dateType isEqualToString:@"command"]){
        return 10;
    }
    if(paraModel.readOnly){
        return 60;
    }
    return 60;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    RHDevParaModel *paraModel = self.dataArray[section];
//    if(paraModel.readOnly){
//        UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 8)];
//        footView.backgroundColor = CFTabViewBgColor;
//        footView.clipsToBounds = YES;
//        UIView *cornerView = [[UIView alloc]initWithFrame:CGRectMake(15, -12, kUI_WINDOW_W-30, 20)];
//        cornerView.backgroundColor = [UIColor whiteColor];
//        cornerView.layer.cornerRadius = 8;
//        cornerView.layer.maskedCorners = kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
//        [footView addSubview:cornerView];
//        return footView;
//    }
    
    CGFloat height = 60;
    RHDevParaModel *rowModel = [paraModel.thresholdParamConfigVos firstObject];
    if([rowModel.dateType isEqualToString:@"command"]){
        height = 10;
    }
    
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, height)];
    footView.backgroundColor = CFTabViewBgColor;
    
    UIView *cornerView = [[UIView alloc]initWithFrame:CGRectMake(15, 0, kUI_WINDOW_W-30, height)];
    cornerView.backgroundColor = [UIColor whiteColor];
    cornerView.layer.cornerRadius = 8;
    cornerView.layer.maskedCorners = kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
    [footView addSubview:cornerView];
    
    if(![rowModel.dateType isEqualToString:@"command"]){
        QMUIButton *submitBtn = [[QMUIButton alloc]init];
        [submitBtn setTitle:@"提交".rh_localized forState:UIControlStateNormal];
        [submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [submitBtn.titleLabel setFont:kSYSTEMFONT(14)];
        submitBtn.backgroundColor = CMainColorGreen;
        submitBtn.layer.cornerRadius = 17;
        [cornerView addSubview:submitBtn];
        kWeakSelf;
        [[submitBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf.view endEditing:YES];
            [weakSelf checkPassword:paraModel];
        }];
       
        [submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(cornerView).offset(-cornerView.width*0.25);
            make.centerY.mas_offset(0);
            make.height.offset(kScaleW(35));
            make.width.offset(kScaleW(90));
        }];
        
        submitBtn.enabled = paraModel.canCommit;
        //master  pack 时间校准只留设置  不用读取
//        if([paraModel.thresholdCode isEqualToString:@"Ems_Systime"]){
//            [submitBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
//                make.centerX.equalTo(cornerView);
//                make.centerY.mas_offset(0);
//                make.height.offset(kScaleW(35));
//                make.width.offset(kScaleW(90));
//            }];
//            return footView;
//        }
        
        QMUIButton *readBtn = [[QMUIButton alloc]init];
        [readBtn setTitle:@"读取".rh_localized forState:UIControlStateNormal];
        [readBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [readBtn.titleLabel setFont:kSYSTEMFONT(14)];
        readBtn.backgroundColor = CMainColorGreen;
        readBtn.layer.cornerRadius = 17;
        [cornerView addSubview:readBtn];
        [[readBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf readParamData:paraModel];
        }];
       
        [readBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(cornerView).offset(cornerView.width*0.25);
            make.centerY.mas_offset(0);
            make.height.offset(kScaleW(35));
            make.width.offset(kScaleW(90));
        }];
        
        //如果只读
        if (paraModel.readOnly) {
            submitBtn.hidden = YES;
            [readBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_offset(0);

            }];
        }
    }
    
    
    return footView;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 55)];
    headView.backgroundColor = CFTabViewBgColor;
    
    UIView *containView = [[UIView alloc]initWithFrame:CGRectMake(15, 10, headView.width-30, 45)];
    containView.backgroundColor = UIColor.whiteColor;
    containView.layer.cornerRadius = 8;
    containView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    [headView addSubview:containView];
    
    QMUILabel *titleLab = [[QMUILabel alloc]initWithFrame:CGRectMake(15, 0, containView.width-30, 45)];
    titleLab.numberOfLines = 2;
//    titleLab.adjustsFontSizeToFitWidth = YES;
//    titleLab.minimumScaleFactor = 0.5;
    RHDevParaModel *paraModel = self.dataArray[section];
    
    if([paraModel.dateType isEqualToString:@"command"]){
        titleLab.text = @"指令".rh_localized;
    }else{
        titleLab.text = paraModel.thresholdName;
    }
    
    
    titleLab.textColor = [UIColor colorWithHexString:@"3F4443" alpha:01];
    titleLab.font = [UIFont systemFontOfSize:15];
    
    UIView *line = [[UIImageView alloc]initWithFrame:CGRectMake(10, 45, kUI_WINDOW_W-20-20, 1)];
    line.backgroundColor = kCOLOR_HEX(@"EBEDF0");
    [containView addSubview:line];
    [containView addSubview:titleLab];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(20);
            make.right.mas_offset(-20);
            make.bottom.mas_offset(-1);
            make.height.offset(1);
    }];
    return headView;
  
    
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    kWeakSelf;
    RHDevParaModel *paraModel = self.dataArray[indexPath.section];
    RHDevParaModel *settingModel = paraModel.thresholdParamConfigVos[indexPath.row];
    //指令
    if([settingModel.dateType isEqualToString:@"command"]){
        RHParaSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:SettingCommandCell];
        [cell setParaModel:paraModel.thresholdParamConfigVos[indexPath.row] deviceTypeCode:self.deviceModel.deviceTypeCode endPointCode:self.endPointTypeModel.endpointTypeCode];
        cell.commandBlock = ^{
            [weakSelf checkPassword:settingModel];
        };
        cell.selectBlock = ^{
            [weakSelf selectAction:settingModel];
        };
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
   
    RHParaSettingCell *settingCell;
    if(settingModel.isEnum && ![settingModel.dateType isEqualToString:@"command"]){//枚举
        settingCell = [tableView dequeueReusableCellWithIdentifier:SettingSelectCell];
        settingCell.selectBlock = ^{
            [weakSelf selectAction:settingModel];
        };
    }
    //加减
    else if([settingModel.dateType isEqualToString:@"int"]||[settingModel.dateType isEqualToString:@"float"])
    {
        settingCell = [tableView dequeueReusableCellWithIdentifier:SettingAddSubCell];
    }else if ([settingModel.dateType isEqualToString:@"boolean"]){//开关
        settingCell = [tableView dequeueReusableCellWithIdentifier:SettingSwitchCell];
    }else if([settingModel.dateType isEqualToString:@"string"]){//文本输入
        settingCell = [tableView dequeueReusableCellWithIdentifier:SettingTextInputCell];
    }else if([settingModel.dateType isEqualToString:@"dateTime"]){//时间
        if([settingModel.paramName isEqualToString:@"Inv3_systemTime"]||
           [settingModel.paramName isEqualToString:@"Ems_systemTime"]){
            //系统校准时间选择
            settingCell = [tableView dequeueReusableCellWithIdentifier:SettingSystemTimeCell];
            settingCell.dateBlock = ^{
                [weakSelf dateAction:settingModel];
            };
        }else{
            //充放电时间选择
            settingCell = [tableView dequeueReusableCellWithIdentifier:SettingDateCell];
            settingCell.dateBlock = ^{
                [weakSelf selectTimeAction:settingModel];
            };
        }
    }
    [settingCell setParaModel:settingModel deviceTypeCode:self.deviceModel.deviceTypeCode endPointCode:self.endPointTypeModel.endpointTypeCode] ;
    settingCell.selectionStyle = UITableViewCellSelectionStyleNone;
    if(settingCell == nil){
        return [UITableViewCell new];
    }
    
    return settingCell;
}



-(UIView *)listView
{
    return self.view;
}

@end
